const router = require('koa-router')()
const userService = require('../controllers/mySqlControll.js')
const jwt = require('../untils/jwt.js')
const { getDetailedDateTime } = require('../untils/timeUtil.js')

// 获取订单的数据表
router.get('/getOrderData', async (ctx, next) => {
  try {
    const result = await userService.getOrder()
    if (!!result.length) {
      ctx.body = {
        msgType: '8000',
        code: 0,
        data: result,
        msg: '查询成功'
      }
    }
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 1,
      data: error,
      msg: '服务器异常'
    }
  }
})


// 获取订单的数据表名
router.get('/getOrderAnnotations', async (ctx, next) => {
  try {
    const result = await userService.getOrderAnnotations()
    if (!!result.length) {
      ctx.body = {
        msgType: '8000',
        code: 0,
        data: result,
        msg: '查询成功'
      }
    }
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 1,
      data: error,
      msg: '服务器异常'
    }
  }
})


// 删除订单的数据
router.post('/deleteOrder', async (ctx, next) => {
  const { order_id } = ctx.request.body
  // console.log(order_id);
  try {
    const results = await Promise.all(order_id.map(async (id) => {
      return await userService.deleteOrder(id);
    }));
    const affectedRows = results.reduce((total, result) => total + result.affectedRows, 0); // 获取所有删除操作受影响的行数总和
    // console.log(affectedRows);
    if (affectedRows !== 0) {
      ctx.body = {
        msgType: '8000',
        code: 0,
        data: '',
        msg: '删除成功'
      }
    } else {
      ctx.body = {
        msgType: '8002',
        code: 0,
        data: '',
        msg: '删除失败'
      }
    }
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      data: error,
      msg: '服务器异常'
    }
  }
})


// 查找订单的数据
router.post('/searchOrder', async (ctx, next) => {
  const { order_id, tatus } = ctx.request.body
  // console.log(order_id, tatus);
  try {
    await userService.searchOrder(order_id, tatus).then(res => {
      if (!!res.length) {
        ctx.body = {
          msgType: '8000',
          code: 0,
          data: res,
          msg: '查找成功'
        }
      } else {
        ctx.body = {
          msgType: '8000',
          code: 0,
          data: [],
          msg: '查找成功'
        }
      }
    })
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      data: error,
      msg: '服务器异常'
    }
  }
})



// 增加购物车
router.post('/addShoppingCart', async (ctx, next) => {
  const { user_id, product_id, quantity, price, image_url, description, product_name,inventory } = ctx.request.body
  // console.log(user_id, product_id, quantity, price,description,product_name);
  // console.log(inventory);
  try {
    const result = await userService.isInShoppingCart(product_id)
    // console.log(result);
    if (!!result.length) {
      ctx.body = {
        msgType: '8003',
        code: 0,
        data: '',
        msg: '商品已存在购物车'
      }
    } else {
      await userService.addShoppingCart([user_id, product_id, quantity, price, image_url, description, product_name,inventory]).then(res => {
        if (res.affectedRows !== 0) {
          ctx.body = {
            msgType: '8000',
            code: 0,
            msg: '添加成功'
          }
        }
      }
      )
    }

  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      data: error,
      msg: '服务器异常'
    }
  }
})


// 获取购物车信息
router.get('/getShoppingCart', async (ctx, next) => {
  const { user_id } = ctx.request.query
  // console.log(user_id);
  try {
    await userService.getShoppingCart(user_id).then(res => {
      if (!!res.length) {
        ctx.body = {
          msgType: '8000',
          code: 0,
          data: res,
          msg: '查找成功'
        }
      } else {
        ctx.body = {
          msgType: '8000',
          code: 0,
          data: [],
          msg: '查找成功'
        }
      }
    })
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      data: error,
      msg: '服务器异常'
    }
  }
})

// 修改商品数量永久存储
router.post('/changeQuantityInShopping', async (ctx, next) => {
  const { quantity, id } = ctx.request.body
  console.log(quantity);
  try {
    await userService.changeQuantityInShopping(quantity, id).then(res => {
      if (res.affectedRows !== 0) {
        ctx.body = {
          msgType: '8000',
          code: 0,
          msg: '修改中'
        }
      } else {
        ctx.body = {
          msgType: '8002',
          code: 0,
          msg: '修改失败'
        }
      }
    }
    )
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      data: error,
      msg: '服务器异常'
    }
  }
})

// 删除购物车的数据
router.post('/deleteShoppingData', async (ctx, next) => {
  const { id } = ctx.request.body
  // console.log(id);
  try {
    const results = await Promise.all(id.map(async (id) => {
      return await userService.deleteShoppingData(id);
    }));
    const affectedRows = results.reduce((total, result) => total + result.affectedRows, 0); // 获取所有删除操作受影响的行数总和
    // console.log(affectedRows);
    if (affectedRows !== 0) {
      ctx.body = {
        msgType: '8000',
        code: 0,
        data: '',
        msg: '删除成功'
      }
    } else {
      ctx.body = {
        msgType: '8002',
        code: 0,
        data: '',
        msg: '删除失败'
      }
    }
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      data: error,
      msg: '服务器异常'
    }
  }
})

// 通过id 查询具体购物车数据
router.post('/getShoppingDataFromId', async (ctx, next) => {
  const { id } = ctx.request.body;
  const ids = JSON.parse(id.replace(/'/g, ''));
  try {
    const response = await userService.getShoppingDataFromId(ids);
    if (response.length > 0) {
      ctx.body = {
        msgType: '8000',
        code: 0,
        data: response,
        msg: '查询成功'
      };
    } else {
      ctx.body = {
        msgType: '8002',
        code: 0,
        data: '',
        msg: '查询失败'
      };
    }
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      data: error,
      msg: '服务器异常'
    };
  }
});

// 添加订单到orderItems，记录买了几件物品
router.post('/addOrderItemsSchedule', async (ctx, next) => {
  const { order_id, product_id, quantity, unit_price, subtotal_price,product_name,product_image,product_description,created_at} = ctx.request.body
  // console.log(product_name,product_description,created_at);
  
  // console.log(order_id, product_id, quantity, unit_price, subtotal_price);
  try {
    const result = await userService.addOrderItemsSchedule([order_id, product_id, quantity, unit_price, subtotal_price,product_name,product_image,product_description,created_at])
    if (result.affectedRows !== 0) {
      ctx.body = {
        msgType: '8000',
        code: 0,
        msg: '购买成功'
      }
    } else {
      ctx.body = {
        msgType: '8002',
        code: 0,
        msg: '购买失败'
      }
    }
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      data: error,
      msg: '服务器异常'
    }
  }
})

// 添加订单到orders
router.post('/addOrders', async (ctx, next) => {
  const { shipping_address, phone, name, user_id, total_amount,created_at,status } = ctx.request.body
  // console.log(shipping_address, phone, name, user_id, total_amount);
  try {
    const result = await userService.addOrders([shipping_address, phone, name, user_id, total_amount,created_at,status]);
    // console.log(result);
    if (result.affectedRows !== 0) {
      ctx.body = {
        msgType: '8000',
        code: 0,
        msg: '购买成功',
        order_id:result.insertId
      }

    } else {
      ctx.body = {
        msgType: '8002',
        code: 0,
        msg: '购买失败'
      }
    }
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      data: error,
      msg: '服务器异常'
    }
  }
})


// 通过user_id获取订单信息 
router.post('/getOrderFromId', async (ctx, next) => {
  const { user_id} = ctx.request.body;
  try {
    const response = await userService.getOrderFromId(user_id);
    if (response.length > 0) {
      ctx.body = {
        msgType: '8000',
        code: 0,
        data: response,
        msg: '查询成功'
      };
    } else {
      ctx.body = {
        msgType: '8002',
        code: 0,
        data: '',
        msg: '查询失败'
      };
    }
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      data: error,
      msg: '服务器异常'
    };
  }
});


// 通过order_id获取订单信息 
router.post('/getOrderFromOrderId', async (ctx, next) => {
  const { order_id} = ctx.request.body;
  // console.log(order_id);
  try {
    const response = await userService.getOrderFromOrderId(order_id);
    if (response.length > 0) {
      ctx.body = {
        msgType: '8000',
        code: 0,
        data: response,
        msg: '查询成功'
      };
    } else {
      ctx.body = {
        msgType: '8002',
        code: 0,
        data: '',
        msg: '查询失败'
      };
    }
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      data: error,
      msg: '服务器异常'
    };
  }
});


// 修改订单的状态
router.post('/changeOrderStatus', async (ctx, next) => {
  const { status, order_id } = ctx.request.body
  // console.log(status, order_id);
  try {
    await userService.changeOrderStatus(status,order_id).then(res => {
      if (res.affectedRows !== 0) {
        ctx.body = {
          msgType: '8000',
          code: 0,
          msg: '修改中'
        }
      } else {
        ctx.body = {
          msgType: '8002',
          code: 0,
          msg: '修改失败'
        }
      }
    }
    )
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      data: error,
      msg: '服务器异常'
    }
  }
})

// 修改订单的库存
router.post('/changeShoppingInventory', async (ctx, next) => {
  const {inventory, product_id} = ctx.request.body
  console.log(inventory, product_id);
  try {
    await userService.changeShoppingInventory(inventory, product_id).then(res => {
      if (res.affectedRows !== 0) {
        ctx.body = {
          msgType: '8000',
          code: 0,
          msg: '修改中'
        }
      } else {
        ctx.body = {
          msgType: '8002',
          code: 0,
          msg: '修改失败'
        }
      }
    }
    )
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      data: error,
      msg: '服务器异常'
    }
  }
})

// 当取消订单时，修改库存
router.post('/changeCancelShoppingInventory', async (ctx, next) => {
  const {inventory, product_id} = ctx.request.body
  console.log(inventory, product_id);
  try {
    await userService.changeCancelShoppingInventory(inventory, product_id).then(res => {
      if (res.affectedRows !== 0) {
        ctx.body = {
          msgType: '8000',
          code: 0,
          msg: '修改中'
        }
      } else {
        ctx.body = {
          msgType: '8002',
          code: 0,
          msg: '修改失败'
        }
      }
    }
    )
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      data: error,
      msg: '服务器异常'
    }
  }
})

// 通过order_id获取订单的信息
// getOrderUseOrderId
router.post('/getOrderUseOrderId', async (ctx, next) => {
  const { order_id} = ctx.request.body;
  // console.log(order_id);
  try {
    const response = await userService.getOrderUseOrderId(order_id);
    if (response.length > 0) {
      ctx.body = {
        msgType: '8000',
        code: 0,
        data: response,
        msg: '查询成功'
      };
    } else {
      ctx.body = {
        msgType: '8002',
        code: 0,
        data: '',
        msg: '查询失败'
      };
    }
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      data: error,
      msg: '服务器异常'
    };
  }
});


// 统计表
router.get('/showCountList', async (ctx, next) => {
  // const { status} = ctx.request.body;
  // console.log(status);
  try {
    const response = await userService.showCountList()
    // console.log(response);
    if (response.length > 0) {
      ctx.body = {
        msgType: '8000',
        code: 0,
        data: response,
        msg: '查询成功'
      };
    } else {
      ctx.body = {
        msgType: '8002',
        code: 0,
        data: '',
        msg: '查询失败'
      };
    }
  } catch (error) {
    ctx.body = {
      msgType: '8002',
      code: 0,
      data: error,
      msg: '服务器异常'
    };
  }
});

// 查找商品的名字，作为统计表
router.post('/serachShoppingCount', async (ctx, next) => {
  const {product_name} = ctx.request.body
  // console.log(product_name);
  try {
    // console.log(searchName, selectioned);
    await userService.serachShoppingCount(product_name).then(res=>{
      // console.log(res);
      // ctx.status=8000
      if (!!res.length) {
        ctx.body = {
          msgType:'8000',
          code: 0,
          data: res,
          msg: '查找成功',
        }
      }else{
        ctx.body = {
          msgType:'8002',
          code: 0,
          data: res,
          msg: '查找失败',
        }
      }
      
    })
  } catch (error) {
    ctx.body = {
      code: 0,
      data: error,
      msg: '服务器异常',
    }
  }
})


module.exports = router